import { Upload, message, Form } from 'antd';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import React from 'react';
function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}

function beforeUpload(file) {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('只能选择JPG/PNG格式!');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('图片必须小于2M!');
  }
  return isJpgOrPng && isLt2M;
}
class UploadImg extends React.Component {
  state = {
    loading: false,
    imageUrl: false,
  };

  componentDidMount() {
    // const { dispatch, match } = this.props;
    this.setState({
      imageUrl: this.props.imgUrl,
    });
  }

  handleChange = (info) => {
    getBase64(info.file.originFileObj, (imageUrl) => {
      this.setState({
        imageUrl,
        loading: false,
      });
      this.props.handleSetFacePicture(imageUrl);
    });
  };

  render() {
    const uploadButton = (
      <div>
        {this.state.loading ? <LoadingOutlined /> : <PlusOutlined />}
        <div className="ant-upload-text">点击上传</div>
      </div>
    );
    const { imageUrl } = this.state;
    return (
      <Upload
        name="multipartFiles"
        listType="picture-card"
        showUploadList={false}
        beforeUpload={beforeUpload}
        onChange={this.handleChange}
      >
        {imageUrl ? (
          <img src={imageUrl} alt="avatar" style={{ maxWidth: '100%', maxHeight: '100%' }} />
        ) : (
          uploadButton
        )}
      </Upload>
      // </FormItem>
    );
  }
}

export default UploadImg;
